package br.edu.ufcg.lsd.wbis.control.equipment;

import java.util.List;

import br.edu.ufcg.lsd.wbis.common.HibernateDAO;

public class HibernateEquipmentDAO extends HibernateDAO implements EquipmentDAO {

	public HibernateEquipmentDAO(){
		super();
	}

	@Override
	public void addEquipment(Equipment equipment){
		session.beginTransaction();
		session.save(equipment);
		session.getTransaction().commit();
	}
	
	@Override
	public void removeEquipment(Equipment equipment){
		session.beginTransaction();
		session.delete(equipment);
		session.getTransaction().commit();
	}
	
	@Override
	public void updateEquipment(Equipment equipment){
		session.beginTransaction();
		session.update(equipment);
		session.getTransaction().commit();
	}
	
	@Override
	public <T extends Equipment> List<T> getEquipments(Class<T> equipmentClazz) {
		return getEquipments(equipmentClazz, "");
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T extends Equipment> List<T> getEquipments(Class<T> equipmentClazz, String restrictions) {
		String whereClause = restrictions.equals("")? "" : " where " + restrictions;
		session.beginTransaction();
		List<T> allEquipments = session.createQuery("from " + equipmentClazz.getCanonicalName() + whereClause).list();
		session.getTransaction().commit();
		return allEquipments;
	}



	@Override
	public <T extends Equipment> T getEquipment(Class<T> equipmentClazz, String inventoryCode) {
		return getEquipment(equipmentClazz, inventoryCode, "");
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T extends Equipment> T getEquipment(Class<T> equipmentClazz,
			String inventoryCode, String restrictions) {
		String whereClause = " where inventoryCode=\'" + inventoryCode + "\'" + (restrictions.equals("")? "" : " and " + restrictions);
		session.beginTransaction();
		T equipment = (T)session.createQuery("from " + equipmentClazz.getCanonicalName() + whereClause).uniqueResult();
		session.getTransaction().commit();
		return equipment;
	}


}
